package org.kalai.unifypay.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.kalai.unifypay.SessionManager;
import org.kalai.unifypay.bean.Bizcnf;
import org.kalai.unifypay.bean.Member;
import org.kalai.unifypay.bean.Transflow;
import org.kalai.unifypay.util.CommonUtil;
import org.kalai.unifypay.util.DataDao;
import org.kalai.unifypay.util.ProxyPayUtil;

import com.alibaba.fastjson.JSON;

@WebServlet(urlPatterns="/ZhongxNotify")
public class ZhongxNotify extends HttpServlet {
	private static final Logger logger = Logger.getLogger(ZhongxNotify.class);
	private static final long serialVersionUID = -3780765180272044514L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
		try {
			String ret = CommonUtil.getResponse(req);
			if (ret == null) logger.error("中信银行异步通知接收数据错误！");
			// 解析请求内容
			Document reqDoc = DocumentHelper.parseText(ret);
			Element msgEl = reqDoc.getRootElement();
			String status = msgEl.elementText("status");
			if (!"0".equals(status))  logger.error("中信银行异步通知通讯失败:"+status);
			String resultCode = msgEl.elementText("result_code");
			if (!"0".equals(resultCode))  logger.error("中信异步通知错误:" + msgEl.elementText("err_code") + "-" + msgEl.elementText("err_msg"));
			String payResult = msgEl.elementText("pay_result");
			String payInfo = msgEl.elementText("pay_info");
			String tranxSN = msgEl.elementText("out_trade_no");
			String totalFee = msgEl.elementText("total_fee");
			payResult = "0".equals(payResult) ? "00" : payResult;
			payInfo = "0".equals(payResult) ? "交易成功" : payInfo;
			logger.info("接收到中信异步通知："+payResult+"-"+tranxSN+"-"+totalFee);
			boolean isok = "00".equals(payResult);
			Transflow transflow = DataDao.getInstance().getTransflow(tranxSN);
			if(transflow == null) throw new RuntimeException(String.format("交易信息不存在[%s,%s,%s]", tranxSN, totalFee, payResult));
			if(transflow.getStatus() == 1){//未处理的订单才进行处理
				Member member = DataDao.getInstance().getMember(transflow.getMemberNo());
				if (member == null) throw new RuntimeException("商户信息不存在:"+transflow.getMemberNo());
				//更新交易表
				DataDao.getInstance().updateTransflow(tranxSN, transflow.getPayAccount(), Long.valueOf(totalFee), isok ? 2 : 3, payResult, payInfo);
				String bizcode = transflow.getBizcode();
				Bizcnf bizcnf = DataDao.getInstance().getBizcnfByCode(bizcode);
				//异步通知账单系统
				CommonUtil.notifyTransFlow(transflow);
				if(isok && bizcnf.getPattern() == 0){//D0交易成功后实时代付出去
					String settNo = CommonUtil.generSettNo();
					boolean flag = DataDao.getInstance().addSettlement(tranxSN, settNo, bizcode, member, transflow.getTransAmt() - transflow.getTransFee(), 1);
					if (flag) ProxyPayUtil.proxyPay(settNo, member, ((Double)(transflow.getTransAmt() * 100 - transflow.getTransFee() * 100)).longValue(), bizcode, true);
				}
				//异步通知用户
				String url = transflow.getNotifyUrl();
				String partnerCode = transflow.getPartnerCode();
				String secret = DataDao.getInstance().getPartnerByCode(partnerCode).getPartnerSecret();
				if(url != null && !"".equals(url)) 
					CommonUtil.notifyMessage(url, partnerCode, secret, tranxSN, transflow.getOrderNo(), transflow.getTransAmt(), payResult, payInfo);
				//websocket推送消息
				Map<String, Object> result = CommonUtil.createRespMap(payResult, payInfo);
				SessionManager.getInstance().broadcast(tranxSN, JSON.toJSONString(result));
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			CommonUtil.responseObject(response, "success");
		}
	}
}
